/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

/**
 * @author USER
 */
public class TheBirdMIDlet extends MIDlet implements CommandListener {

    //public int jumRecord;
    final static int JUM = 220;
    public static String[] daftarNilai = new String[5000];
    public static int[] limaNilai = new int[JUM];
    public static int CLICKED = 0;
    protected Display display;      //reference to display
    private Command cmdExit;
    //canvas
    private GrassCanvas grassCanvas;
    private DessertCanvas dessertCanvas;
    private SnowCanvas snowCanvas;
    private MenuCanvas menuCanvas;
    private HelpCanvas helpCanvas;
    private AboutCanvas aboutCanvas;

    /* highscores */
    private List list, menu;
    //private Alert alert;
    private ChoiceGroup choicegroup;
    private RecordStore rsScore;
    private RecordEnumeration reScore;
    private RecordStore rsLevel;
    private RecordEnumeration reLevel;
    //untuk proses entry data
    private Form entri;
    private TextField tfNama, tfNoTelp;
    private final Command cmdKeluar = new Command("Keluar", Command.EXIT, 1);
    private final Command cmdPilih = new Command("Pilih", Command.OK, 1);
    private final Command cmdSimpan = new Command("Simpan", Command.SCREEN, 1);
    private final Command cmdHapus = new Command("Hapus", Command.SCREEN, 1);
    private final Command cmdKembali = new Command("Kembali", Command.BACK, 1);
    public static int LEVEL = 0;
//    /Player player;
    //boolean isAudio = false;
    //public static boolean isVibrate = false;

    public TheBirdMIDlet() {

        /*-start---*/
        LEVEL = 1;
        for (int i = 0; i < JUM; i++) {
            daftarNilai[i] = "0";
        }

        display = Display.getDisplay(this);
        //isAudio = true;
        //isVibrate = true;

        //alert = new Alert(null);
        //alert.setTimeout(Alert.FOREVER);

        list = new List(null, Choice.IMPLICIT);
        menu = new List(null, Choice.IMPLICIT);
        rsScore = null;
        rsLevel = null;

        //membuka atau memuat baru record store
        try {
            rsScore = RecordStore.openRecordStore("dbb_score6", true);
            rsLevel = RecordStore.openRecordStore("dbb_level6", true);
        } catch (RecordStoreException rse) {
            //alert.setString("Record store tidak dapat dibuka.\nAplikasi akan dihentikan");
            //alert.setType(AlertType.ERROR);
            //display.setCurrent(alert, null);
            System.exit(1);
        }
        /*-end---*/

        /* game */
        //display = Display.getDisplay(this);

        aboutCanvas = new AboutCanvas(this, display);
        helpCanvas = new HelpCanvas(this, display);
        menuCanvas = new MenuCanvas(this, display);

        /*
        try {
        InputStream in = getClass().getResourceAsStream("/cobi2.wav");
        player = Manager.createPlayer(in, "audio/x-wav");
        } catch (IOException ex) {
        ex.printStackTrace();
        } catch (MediaException ex) {
        ex.printStackTrace();
        }
         * 
         */
    }

    public void startApp() {
        showMenuCanvas();
        //setHighScores();
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    /*
    public void commandAction(Command c, Displayable d) {
    if (c == cmdExit) {
    destroyApp(true);
    notifyDestroyed();
    }
    }
     * 
     */
    public void exit() {
        menuCanvas.stop();
        if (grassCanvas != null) {
            grassCanvas.stop();
        }
        if (dessertCanvas != null) {
            dessertCanvas.stop();
        }
        if (snowCanvas != null) {
            snowCanvas.stop();
        }
        destroyApp(true);
        notifyDestroyed();
    }

    public void showMenuCanvas() {

        //stopAudio();
        CLICKED = 0;

        if (grassCanvas != null) {
            grassCanvas.stop();
        }

        if (dessertCanvas != null) {
            dessertCanvas.stop();
        }
        if (snowCanvas != null) {
            snowCanvas.stop();
        }

        grassCanvas = null;
        dessertCanvas = null;
        snowCanvas = null;

        menuCanvas.start();
        menuCanvas.setGeserKiri();
        menuCanvas.isPaused = false;
        menuCanvas.running = true;
        display.setCurrent(menuCanvas);
    }

    public void sortHighScore() {
        getRecordNilai();
        for (int i = 0; i < JUM; i++) {
            //String aString = "78";
            //System.out.println(daftarNilai[i]);
            int aInt = Integer.parseInt(daftarNilai[i]);
            limaNilai[i] = aInt;
            //System.out.println("sblm : " + limaNilai[i]);
        }
        //int maks = limaNilai[0];
        int temp = 0;
        for (int i = JUM - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                if (limaNilai[j] < limaNilai[j + 1]) {
                    temp = limaNilai[j];
                    limaNilai[j] = limaNilai[j + 1];
                    limaNilai[j + 1] = temp;
                }
            }
        }
        /*
         * int i, j;
        for (i=jumItem-1; i>0; i–)
        {
        for (j=0; j<i; j++)
        {
        if (larik[j] > larik[j+1])
        tukar(j, j+1);
        }

        System.out.println(“Hasil langkah ke ” + (-(i-jumItem)));
        baca_larik();
        }
         */

        /*
        for (int i = 0; i < JUM; i++) {
            //String aString = "78";
            //System.out.println("ude cin : " + limaNilai[i]);
        }
         * 
         */
    }

    public void showHighScores(int value, boolean luar) {
        if (luar) { //dlm permaian
            CLICKED = 0;
            if (value > limaNilai[JUM - 1]) {
                tambahScore(String.valueOf(value));
            }
            getRecordNilai();
            sortHighScore();

            if (grassCanvas != null) {
                grassCanvas.stop();
            }

            if (dessertCanvas != null) {
                dessertCanvas.stop();
            }
            if (snowCanvas != null) {
                snowCanvas.stop();
            }

            grassCanvas = null;
            dessertCanvas = null;
            snowCanvas = null;
            menuCanvas.start();
            menuCanvas.setHighScores();
            menuCanvas.setGeserKiri();
            menuCanvas.isPaused = false;
            menuCanvas.running = true;
            //menuCanvas.showNotify()
            display.setCurrent(menuCanvas);
        } else {
            getRecordNilai();
            sortHighScore();
            menuCanvas.setHighScores();
        }

    }


    /*
    private void playAudio() {
    try {
    InputStream in = getClass().getResourceAsStream("/cobi2.wav");
    player = Manager.createPlayer(in, "audio/x-wav");
    //
    //InputStream in = getClass().getResourceAsStream("/cobi.amr");
    //Player player = Manager.createPlayer(in, "audio/amr");
    //Player p = Manager.createPlayer("capture://audio?audio_enc=amr");
    //Player p2 = Manager.createPlayer(recordedInputStream,"audio/amr");
    //player.start();
    //player.setLoopCount(-1);
    player.setLoopCount(-1);
    player.prefetch();
    player.realize();
    player.start();
    } catch (Exception e) {
    //showException(e);
    return;
    }

    }
     * 
     */

    /*
    public void stopAudio() {
    try {
    player.stop();
    player = null;
    } catch (MediaException ex) {
    }
    }
     * 
     */
    public void showGrassCanvas() {
        if (CLICKED < 1) {
            CLICKED = CLICKED + 1;
            grassCanvas = new GrassCanvas(this, 0);
            menuCanvas.stop();
            grassCanvas.stop();
            if (grassCanvas != null) {
                CLICKED = 0;
                display.setCurrent(grassCanvas);
                //playAudio();
                grassCanvas.start();
            }
        }
    }

    public void showDessertCanvas(int score) {
        dessertCanvas = new DessertCanvas(this, score);
        //playAudio();
        dessertCanvas.start();
        display.setCurrent(dessertCanvas);
    }

    public void showSnowCanvas(int score) {
        snowCanvas = new SnowCanvas(this, score);
        //playAudio();
        snowCanvas.start();
        display.setCurrent(snowCanvas);
    }


    /*
    private void setHighScores(){
//--rms--
    menu.setTitle("APLIKASI MANAJEMEN KEUANGAN");
    menu.deleteAll();

    menu.append("Tambah Kategori", null);
    menu.append("Daftar Kategori", null);

    menu.addCommand(cmdKeluar);
    menu.addCommand(cmdPilih);
    menu.setCommandListener(this);
    //display.setCurrent(menu);
    //entriData();

    //tambahScore("yoha", "2423");
    getRecordNilai();
    display.setCurrent(list);
    }
     * 
     */
    public void commandAction(Command c, Displayable d) {
        if (c == cmdExit) {
            destroyApp(true);
            notifyDestroyed();
        }

        if (c == cmdKeluar) {
            destroyApp(false);
            notifyDestroyed();
        } else if (c == cmdPilih) {
            switch (menu.getSelectedIndex()) {
                case 0: {
                    entriData();
                    break;
                }
                case 1: {
                    //getRecordNilai();
                    display.setCurrent(list);
                    break;
                }
            }
        } else if (c == cmdKembali) {
            display.setCurrent(menu);
        } else if (c == cmdSimpan) {
            if (tfNama.getString().equals("") || tfNoTelp.getString().equals("")) {
                //alert.setType(AlertType.ERROR);
//                /alert.setString("Data Kategori dan Budget tidak boleh kosong !");
                //display.setCurrent(alert, entri);
            } else {
                //tambahScore(tfNama.getString(), tfNoTelp.getString());
                //alert.setString("Data baru telah berhasil disimpan");
                //display.setCurrent(alert, menu);
            }
        } else if (c == cmdHapus) {
            int pos = list.getString(list.getSelectedIndex()).indexOf(" [");
            String nama = list.getString(list.getSelectedIndex()).substring(0, pos);
            hapusRecord(nama);
            //alert.setType(AlertType.INFO);
            //alert.setString("Delete sukses");
            //getRecordNilai();
            //display.setCurrent(alert, list);
        }
    }

    public Form entriData() {
        entri = new Form("Entri Data");
        tfNama = new TextField("Kategori :", null, 25, TextField.ANY);
        tfNoTelp = new TextField("Budget :", null, 25, TextField.PHONENUMBER);

        entri.append(tfNama);
        entri.append(tfNoTelp);
        entri.addCommand(cmdSimpan);
        entri.addCommand(cmdKembali);
        entri.setCommandListener(this);
        display.setCurrent(entri);
        return entri;
    }

    public void tambahScore(String noTelp) {
        byte[] temp = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);
            //dos.writeUTF(nama);
            dos.writeUTF(noTelp);
            temp = baos.toByteArray();
        } catch (IOException ioe) {
        }

        try {
            rsScore.addRecord(temp, 0, temp.length);
        } catch (RecordStoreNotOpenException rsnoe) {
        } catch (RecordStoreException rse) {
        }
    }

    public void tambahLevel(String level) {
        byte[] temp = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);
            dos.writeUTF(level);
            temp = baos.toByteArray();
        } catch (IOException ioe) {
        }

        try {
            rsLevel.addRecord(temp, 0, temp.length);
        } catch (RecordStoreNotOpenException rsnoe) {
        } catch (RecordStoreException rse) {
        }
    }

    //public String[] daftarNilai = new String[5];    
    public void getRecordNilai() {
        byte[] temp = null;

        //jumRecord = 0;

        try {
            reScore = rsScore.enumerateRecords(null, null, false);
            reScore.numRecords();
            int idx = 0;
            while (reScore.hasNextElement()) {

                int i = reScore.nextRecordId();
                temp = rsScore.getRecord(i);
                ByteArrayInputStream bais = new ByteArrayInputStream(temp);
                DataInputStream dis = new DataInputStream(bais);

                try {
                    String budget = dis.readUTF();
                    daftarNilai[idx] = budget;
                    idx++;
                } catch (IOException ioe) {
                }
            }
            //list.addCommand(cmdKembali);
            //list.addCommand(cmdHapus);
            //list.setCommandListener(this);
        } catch (InvalidRecordIDException invID) {
        } catch (RecordStoreNotOpenException rsnoe) {
        } catch (RecordStoreException rse) {
        }
        //return daftarNilai;
    }// end lihatRecord

    public void resetScore() {
        try {
            reScore = rsScore.enumerateRecords(null, null, false);
            while (reScore.hasNextElement()) {
                int i = reScore.nextRecordId();
                //temp = rsScore.getRecord(i);
                //ByteArrayInputStream bais = new ByteArrayInputStream(temp);
                //DataInputStream dis = new DataInputStream(bais);

                rsScore.deleteRecord(i);
                //System.out.println("nci " + i);
                /*
                try {

                String vNama = dis.readUTF();
                if (vNama.equals(nama)) {
                rsScore.deleteRecord(i);
                break;
                }
                 *

                rsScore.deleteRecord(i);
                break;
                } catch (IOException ioe) {
                }
                 * 
                 */
            }
        } catch (RecordStoreNotOpenException rsnoe) {
        } catch (RecordStoreException rse) {
        }

        for (int i = 0; i < JUM; i++) {
            daftarNilai[i] = "0";
            limaNilai[i] = 0;
        }
    }

    public void hapusRecord(String nama) {
        byte[] temp = null;

        try {
            reScore = rsScore.enumerateRecords(null, null, false);
            while (reScore.hasNextElement()) {
                int i = reScore.nextRecordId();
                temp = rsScore.getRecord(i);
                ByteArrayInputStream bais = new ByteArrayInputStream(temp);
                DataInputStream dis = new DataInputStream(bais);

                try {
                    String vNama = dis.readUTF();
                    if (vNama.equals(nama)) {
                        rsScore.deleteRecord(i);
                        break;
                    }
                } catch (IOException ioe) {
                }
            }
        } catch (RecordStoreNotOpenException rsnoe) {
        } catch (RecordStoreException rse) {
        }
    }
}
